import { EventBus } from './EventBus';

class WebSocketManager {
    constructor() {
        this.ws = null;
        this.isConnected = false;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.reconnectDelay = 1000; // 1 second
    }

    connect() {
        try {
            console.log('Attempting to connect to WebSocket server...');
            
            
            const currentPath = 'ws://localhost:9081/ws';
            console.log(`Trying WebSocket path: ${currentPath}`);
            
            this.ws = new WebSocket(currentPath);
            
            // 设置连接超时
            const connectionTimeout = setTimeout(() => {
                if (this.ws && this.ws.readyState === WebSocket.CONNECTING) {
                    console.log('WebSocket connection timeout, trying next path...');
                    this.ws.close();
                }
            }, 3000);
            
            this.ws.onopen = (event) => {
                clearTimeout(connectionTimeout);
                console.log('WebSocket connected to Netty server successfully');
                this.isConnected = true;
                this.reconnectAttempts = 0;
                // 触发连接成功事件
                this.onConnectionEstablished && this.onConnectionEstablished();
            };

            this.ws.onmessage = (event) => {
                console.log('Received message from server:', event.data);
                // 处理从服务器接收到的消息
                this.handleMessage(event.data);
            };

            this.ws.onclose = (event) => {
                clearTimeout(connectionTimeout);
                console.log('WebSocket connection closed', event.code, event.reason);
                this.isConnected = false;
                // 只有在非正常关闭时才尝试重连
                if (event.code !== 1000) {
                    this.attemptReconnect();
                }
            };

            this.ws.onerror = (error) => {
                clearTimeout(connectionTimeout);
                console.error('WebSocket error:', error);
                this.isConnected = false;
            };

        } catch (error) {
            console.error('Failed to create WebSocket connection:', error);
            this.attemptReconnect();
        }
    }

    attemptReconnect() {
        if (this.reconnectAttempts < this.maxReconnectAttempts) {
            this.reconnectAttempts++;
            console.log(`Attempting to reconnect... (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
            
            setTimeout(() => {
                this.connect();
            }, this.reconnectDelay * this.reconnectAttempts);
        } else {
            console.error('Max reconnection attempts reached');
        }
    }

    sendMessage(message) {
        if (this.isConnected && this.ws) {
            try {
                this.ws.send(JSON.stringify(message));
                console.log('Message sent to server:', message);
            } catch (error) {
                console.error('Failed to send message:', error);
            }
        } else {
            console.warn('WebSocket not connected, attempting to connect...');
            this.connect();
            // 延迟发送消息，等待连接建立
            setTimeout(() => {
                if (this.isConnected) {
                    this.sendMessage(message);
                }
            }, 1000);
        }
    }

    handleMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log('Received message from server:', message);
            
            // 根据消息类型处理不同的逻辑
            switch (message.type) {
                case 'game_start':
                    console.log('Game start confirmed by server');
                    break;
                case 'player_info':
                    console.log('Player info received:', message.data);
                    break;
                case 'player_id_assigned':
                    // 处理玩家ID分配
                    this.handlePlayerIdAssigned(message.data);
                    break;
                case 'player_update':
                    // 处理其他玩家更新
                    this.handlePlayerUpdate(message.data);
                    break;
                case 'player_join':
                    // 处理新玩家加入
                    this.handlePlayerJoin(message.data);
                    break;
                case 'player_leave':
                    // 处理玩家离开
                    this.handlePlayerLeave(message.data);
                    break;
                case 'player_list':
                    // 处理玩家列表
                    this.handlePlayerList(message.data);
                    break;
                case 'map_data':
                    // 处理地图数据
                    this.handleMapData(message.data);
                    break;
                case 'food_spawn':
                    // 处理食物生成
                    this.handleFoodSpawn(message.data);
                    break;
                case 'spike_spawn':
                    // 处理刺生成
                    this.handleSpikeSpawn(message.data);
                    break;
                case 'chat_message':
                    // 处理聊天消息
                    this.handleChatMessage(message.data);
                    break;
                case 'player_eaten':
                    // 处理玩家被吃掉事件
                    this.handlePlayerEaten(message.data);
                    break;
                default:
                    console.log('Unknown message type:', message.type);
            }
        } catch (error) {
            console.error('Failed to parse message:', error);
        }
    }

    handlePlayerIdAssigned(data) {
        const { playerId } = data;
        // 通过EventBus通知游戏场景
        EventBus.emit('player_id_assigned', playerId);
    }

    handlePlayerUpdate(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('player_update', data);
    }

    handlePlayerJoin(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('player_join', data);
    }

    handlePlayerLeave(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('player_leave', data);
    }

    handlePlayerList(data) {
        // 处理初始玩家列表
        const { players } = data;
        if (players && Array.isArray(players)) {
            players.forEach(player => {
                if (player.playerId !== this.currentPlayerId) {
                    this.handlePlayerJoin(player);
                }
            });
        }
    }

    handleMapData(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('map_data', data);
    }

    handleFoodSpawn(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('food_spawn', data);
    }

    handleSpikeSpawn(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('spike_spawn', data);
    }

    handleChatMessage(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('chat_message', data);
    }

    handlePlayerEaten(data) {
        // 通过EventBus通知游戏场景
        EventBus.emit('player_eaten', data);
    }

    disconnect() {
        if (this.ws) {
            this.ws.close();
            this.isConnected = false;
        }
    }

    // 发送游戏开始消息
    sendGameStart(playerName = 'Player') {
        const message = {
            type: 'game_start',
            data: {
                playerName: playerName,
                timestamp: Date.now()
            }
        };
        this.sendMessage(message);
    }

    // 发送玩家状态更新（包含用户名）
    sendPlayerStatus(playerName, status) {
        const message = {
            type: 'player_status',
            data: {
                playerName: playerName,
                ...status,
                timestamp: Date.now()
            }
        };
        this.sendMessage(message);
    }
}

// 创建单例实例
export const webSocketManager = new WebSocketManager(); 